import aixos from 'axios'
import {getStorage} from "../context";
import Info from "../service/info";
import TokenModel from "../model/token";
import {setStorage} from "../component/RouteTable/RouteTable";
aixos.defaults.timeout = 10000000

// aixos.interceptors.request.use(config => {
//     config.headers['Access-Control-Allow-Origin'] = '*'
//     return config
// }, error => {
//     console.log('eject')
//     console.log(error.config)
// })
// 800 不存在 密码错误
// 801 过期
// 802 用户已存在
// 803 权限不够
const errorCodeMapper = {
    800: '用户不存在或者密码错误',
    801: 'token过期',
    802: '用户已存在',
    803: '权限不够',
}

export const clearStorage = () => {
    let l = localStorage.length
    let keyList = []
    for (let i = 0; i < l; i++) {
        let key = localStorage.key(i)
        keyList.push(key)
    }
    keyList.map(key => localStorage.removeItem(key))
}

aixos.interceptors.request.use(
    config => {

        let url = config.url
        let isTaboo = url.includes('pinbi')

        config.withCredentials = false
        // config.timeout = 6000
        let token = getStorage('token')
        // let token = '123'
        if (token && !isTaboo) {
            config.headers['token'] = `${token}`
        }
        return config
    }, error => {
        return Promise.reject(error)
    })

aixos.interceptors.response.use(res => {
    const data = res.data

    if (data.err) {
        if (data.err === 803) {
            clearStorage()
            Info.error('管理员权限不够')
            const origin = window.location.origin
            window.location = origin + '/login'
        } else if (data.err === 801) {
            // const getRefreshToken =
            const config = res.config
            const url = res.config.url
            const isRefreshTkReq = url.endsWith('refreshtoken')
            if (isRefreshTkReq) {
                Info.error('token已经过期 请重新登陆')
                clearStorage()
                const origin = window.location.origin
                window.location = origin + '/login'
            } else {
                const model = new TokenModel()
                const refreshToken = getStorage('refreshToken')
                return model
                    .fresh({token: refreshToken})
                    .then(res => {
                        const token = res.data.token
                        setStorage({
                            token: token,
                        })
                        config.headers['token'] = `${token}`
                        return aixos(config)
                    })
            }
        } else {
            const errMsg = errorCodeMapper[data.err]
            errMsg ? Info.error(errMsg) : Info.error(data.err)
            return res
        }
    } else {
        return res
    }
})




export class ApiFetch {
    constructor(endPoint, verb = 'post') {
        this.endPoint = endPoint
        this.verb = verb
    }

    async fetch(params, config = {}) {
        const v = this.verb
        const e = this.endPoint
        // console.log(aixos.)
        const resp = await aixos[v](e, params, config)
        return resp
    }

    async fetchByFD(params, config = {}) {
        const fm = new FormData()
        const v = this.verb
        const e = this.endPoint
        for (let [key, value] of Object.entries(params)) {
            fm.append(key, value)
        }
        const resp = await aixos[v](e, fm, config)
        return resp
    }
}

